/*
 * @Author: wangming
 * @Date: 2020-07-15 11:48:47
 * @LastEditors: wangming
 * @LastEditTime: 2022-03-10 10:40:35
 * @Description: file content
 */
/**
 * 消抖
 * @param wait 时间
 */
import { MessageBox } from 'element-ui'
import Vue from 'vue';
import router from '@/router';

export function Debounce(wait = 50) {
  return (target, name, descriptor) => {
    var old_fn = descriptor.value
    var t = 0
    var args = []
    descriptor.value = function (..._args) {
      args = _args
      clearTimeout(t)
      t = setTimeout(() => old_fn.apply(this, args), wait)
    }
    return descriptor
  }
}
/**
 * 节流
 * @param {*} wait
 */
export function Throttle(wait = 50) {
  return (target, name, descriptor) => {
    var old_fn = descriptor.value
    var prev = 0
    descriptor.value = function (...args) {
      var t = Date.now()
      if (t - prev > wait) {
        prev = t
        old_fn.apply(this, args)
      }
    }
    return descriptor
  }
}

/**
 * 二次确认
 * @param {*} options
 */
export function Confirm(options = {}) {
  const option = Object.assign(
    {
      message: '确认提交表单吗？',
      center: true,
      showClose: false,
      title: '提示',
      type: 'warning',
      customClass: 'custom-message-box'
    },
    options
  )
  return (target, name, descriptor) => {
    var old_fn = descriptor.value
    descriptor.value = function (...args) {
      MessageBox.confirm(option.message, option.title, option)
        .then(() => {
          old_fn.apply(this, args)
        })
        .catch(() => {
          // on cancel
        })
    }
    return descriptor
  }
}

/**
 * 单例模态框页面跳转时候自动销毁
 * @param {*} template 
 * @returns 
 */
export function InstanceVm(template) {
  return (target, name, descriptor) => {
    target.instance = null
    target.create = function () {
      if (!this.instance) {
        const BenConstructor = Vue.extend(template);
        this.instance = new BenConstructor({
          el: document.createElement('div'),
        });
        document.body.appendChild(this.instance.$el);
      }
    }
    target.clearVm = function () {
      if (!this.instance) return
      this.instance.$el.remove()
      this.instance.$destroy()
      this.instance = null
    }
    router.afterEach(() => {
      target.clearVm()
    });

  }
}